var upload = angular.module('componentes', []);
upload.directive('sigadUpload', function() {
	var upload = {
		priority : 0,
		templateUrl : 'templates/sigad-upload.html',
		restrict : 'E',
//		scope : {
//			estadoRepresentacaoVisual : '=info',
//			modoDeEdicao:true
//		},
		controller : function($scope) {
			new SigadUploadCtrl($scope);
		}
	};
	return upload;
});

function SigadUploadCtrl(scope) {
	scope.modoDownload = scope.modoDeEdicao;
	scope.setFiles = function(element) {
		scope.$apply(function(scope) {
			console.log('files:', element.files);
			// Turn the FileList object into an Array
			scope.files = [];
			for (var i = 0; i < element.files.length; i++) {
				scope.files.push(element.files[i]);
			}
			scope.progressVisible = false;
		});
	};

	scope.mostrarComponenteDeUpload = function() {
		scope.alterouRepresentacao=true;
		scope.modoDownload=false;
	}

	scope.uploadFile = function() {
		var fd = new FormData();
		for ( var i in scope.files) {
			fd.append("uploadedFile", scope.files[i]);
		}
		var xhr = new XMLHttpRequest();
		xhr.upload.addEventListener("progress", uploadProgress, false);
		xhr.addEventListener("load", uploadComplete, false);
		xhr.addEventListener("error", uploadFailed, false);
		xhr.upload.addEventListener('loadend', function(e) {
			alert('Arquivo enviado com sucesso!');
		});
		xhr.open("POST", "fileupload");
		xhr.send(fd);
		scope.progressVisible = true;
	};

	function uploadProgress(evt) {
		scope.$apply(function() {
			if (evt.lengthComputable) {
				scope.progress = Math.round(evt.loaded * 100 / evt.total);
			} else {
				scope.progress = 'unable to compute';
			}
		});
	}

	function uploadComplete(evt) {
		/* This event is raised when the server send back a response */

	}

	function uploadFailed(evt) {
		alert("There was an error attempting to upload the file.");
	}

	scope.uploadCanceled = function() {
//		scope.$apply(function() {
			scope.progressVisible = false;
//		});
		scope.modoDownload = true;
		scope.alterouRepresentacao=false;
	};
};